<template>
  <div class="search">
    <div class="search-box">
      <i class="fa fa-search" aria-hidden="true"></i>
      <input
        type="text"
        placeholder="搜索歌曲、歌手、专辑"
        v-model="keywords"
        @keyup.enter="search"
        @input="inputting"
        ref="searchboxws"
      />
      <i class="fa fa-times-circle" v-show="showdel" @click="clearWord"></i>
    </div>
    <hr />
    <component
      :is="showComponent"
      :keywords="keywords"
      @changekeyword="changekeyword"
      @play="$emit('play', $event)"
    >
    </component>
  </div>
</template>
<script>
import SearchHot from "@/components/SearchHot.vue";
import SearchSug from "@/components/SearchSug.vue";
import SearchResult from "@/components/SearchResult.vue";
export default {
  name: "Search",
  data() {
    return {
      showComponent: SearchHot,
      keywords: "",
      showdel: false,
    };
  },
  created() {},
  mounted(){
    this.$refs.searchboxws.focus();
  },
  beforeRouteEnter(to,from,next){
    next(vm=>{
      vm.$nextTick(()=>{
        vm.$refs.searchboxws.focus();
      })
    })
  },
  methods: {
    clearWord() {
      this.keywords = "";
      this.showdel = false;
      this.showComponent = SearchHot;
    },
    search() {
      this.showComponent = SearchResult;
    },
    changekeyword(event) {
      this.keywords = event;
      this.showComponent = SearchResult;
    },
    inputting() {
      if (this.keywords == "") {
        this.showComponent = SearchHot;
      } else {
        this.showdel = true;
        this.showComponent = SearchSug;
      }
    },
  },
  components: {
    SearchHot,
    SearchSug,
    SearchResult,
  },
  watch: {
    keywords(newValue) {
      if (newValue == "" || newValue.length == 0) {
        this.showComponent = SearchHot;
      } else {
        this.showComponent = SearchSug;
      }
    },
  },
};
</script>
<style scoped lang="less">
.search {
  width: 100%;
  background-color: #fafafa;
  .search-box {
    margin: 2px 20px;
    background-color: white;
    border-radius: 40px;
    padding: 5px 50px;
    position: relative;
    i {
      position: absolute;
      font-size: 18px;
      top: 50%;
      transform: translateY(-50%);
      color: #cbcbcb;
      &.fa-search {
        left: 20px;
      }
      &.fa-times-circle {
        right: 10px;
      }
    }
    input {
      height: 25px;
      font-size: 14px;
      background-color: transparent;
      border: none;
      outline: none;
      color: #333;
    }
  }
}
.search {
  hr {
    height: 0px;
    border: none;
    border-bottom: 1px solid rgb(226, 226, 226);
  }
}
</style>